<template>
  <DialogButton
    :submit-loading="addLoading"
    :button-text="Data.addPost.dialogButtonText"
    :dialog-title="Data.addPost.dialogTitle"
    :submit-function="Data.addPost.submitFunction"
    :function-ok="Data.functionOk"
    :dialog-style="dialogStyle"
    @dialog-close="Data.functionOk = false"
  >
    <template #body>
      <div
        v-loading="addLoading"
      >
        <el-form
          :model="Data.addPost.addQuery"
          :rules="addRules"
          label-width="auto"
          style="max-width: 600px"
        >
          <el-form-item
            label="标题"
            prop="title"
          >
            <el-input
              v-model="Data.addPost.addQuery.title"
              placeholder="请输入标题"
            />
          </el-form-item>
          <el-form-item
            label="选择图片"
            prop="img"
          >
            <span
              v-for="(item, index) in Data.addPost.addQuery.files"
              :key="index"
            >
              <img-upload v-model="item.fileUrl" />
              <el-button
                link
                @click="removeFile(index)"
              >
                删除
              </el-button>
              <el-button
                link
                :disabled="index === 0"
                @click="moveUp(index)"
              >
                上移
              </el-button>
              <el-button
                link
                :disabled="index === Data.addPost.addQuery.files.length - 1"
                @click="moveDown(index)"
              >
                下移
              </el-button>
            </span>
            <el-button
              type="primary"
              @click="addFile"
            >
              添加图片
            </el-button>
          </el-form-item>
          <el-form-item
            label="地址"
            prop="location"
          >
            <el-input
              v-model="Data.addPost.addQuery.location"
              placeholder="请输入地址"
            />
          </el-form-item>
          <el-form-item
            label="持续时间"
            prop="time"
          >
            <DateSelect
              @start-time="(time) => { Data.addPost.addQuery.startTime = time }"
              @end-time="(time) => { Data.addPost.addQuery.endTime = time }"
            />
          </el-form-item>
          <el-form-item
            label="目标板块"
            prop="sectionId"
          >
            <el-select
              v-model="Data.addPost.addQuery.sectionId"
              style="width: 240px"
            >
              <el-option
                v-for="item in boardListOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="链接到"
            prop="linkUrl"
          >
            <el-cascader
              v-model="Data.addPost.addQuery.preLinkUrl"
              placeholder="输入搜索或选择"
              :options="options"
              filterable
              clearable
              @change="pushOption(Data.addPost.addQuery.preLinkUrl)"
            />
          </el-form-item>
        </el-form>
        <div>
          <post-content
            :data-form="Data.addPost.addQuery.content"
            @update:data-form="upDateForm"
          />
        </div>
      </div>
    </template>
  </DialogButton>
</template>
<script setup>
import * as api from '@/api/platform/post'
import * as boardApi from '@/api/point/board'
import * as spuApi from '@/api/product/search.js'
import * as postApi from '@/api/platform/post.js'
import DialogButton from '@/components/DialogButton.vue'
import DateSelect from '@/components/DateSelect.vue'
function pushOption (data) {
  if (data !== null) {
    Data.addPost.addQuery.linkUrl = `${data[0]}${data[1]}`
    // console.log(Data.addPost.addQuery.linkUrl)
  }
}

function upDateForm (val) {
  Data.addPost.addQuery.content = val
}

const boardList = ref([])
const boardListOptions = ref([])
const addLoading = ref(false)
const dialogStyle = ref('width: 80%')
const Data = reactive({
  addPost: {
    dialogButtonText: '发布活动',
    dialogTitle: '发布活动',
    submitFunction: () => {
      addLoading.value = true
      // 重新构造imgUrl
      // Data.addPost.addQuery.imgUrl = `${import.meta.env.VITE_APP_BASE_API}/mall4cloud${Data.addPost.addQuery.imgUrl}`
      if (Data.addPost.addQuery.startTime && Data.addPost.addQuery.title) {
        const temp = JSON.parse(JSON.stringify(Data.addPost.addQuery))
        if (temp.files[0].fileUrl == '') {
          temp.files = []
        }
        api.addPost(
          temp
        ).then(() => {
          ElMessage({
            message: '操作成功',
            type: 'success'
          })
          addLoading.value = false
          Data.functionOk = true
          emits('workEnd')
        }).catch(() => {
          ElMessage.error('操作失败')
          addLoading.value = false
        })
      } else {
        ElMessage.error('请填写必要内容')
        addLoading.value = false
      }
    },
    addQuery: {
      title: '',
      content: '',
      location: '市民广场',
      tags: 6666666,
      sectionId: 1,
      preLinkUrl: null,
      linkUrl: null,
      files: [
        {
          fileUrl: '',
          seq: 0,
          fileType: 'bmp'
        }
      ],
      startTime: '',
      endTime: ''
    }
  },
  functionOk: false
})

const addRules = {
  time: [
    { required: true, message: '请选择时间', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入标题', trigger: 'change' }
  ]
}

// linkUrl字段
const options = ref([
  {
    value: 'activitySection://',
    label: '活动板块',
    children: [
      {
        value: null,
        label: '没有'
      }
    ]
  },
  {
    value: 'communitySection://',
    label: '粉丝社区板块',
    children: [
      {
        value: null,
        label: '没有'
      }
    ]
  },
  {
    value: 'post://',
    label: '帖子',
    children: [
      {
        value: null,
        label: '没有'
      }
    ]
  },
  {
    value: 'product://',
    label: '商品',
    children: [
      {
        value: null,
        label: '没有'
      }
    ]
  }
])

function addFile () {
  Data.addPost.addQuery.files.push({
    fileUrl: '',
    seq: Data.addPost.addQuery.files.length,
    fileType: 'bmp'
  })
}

function removeFile (index) {
  Data.addPost.addQuery.files.splice(index, 1)
  // 重新设置seq
  Data.addPost.addQuery.files.forEach((file, i) => {
    file.seq = i
  })
}
function moveUp (index) {
  if (index > 0) {
    const temp = Data.addPost.addQuery.files[index]
    Data.addPost.addQuery.files[index] = Data.addPost.addQuery.files[index - 1]
    Data.addPost.addQuery.files[index - 1] = temp
  }
}

function moveDown (index) {
  if (index < Data.addPost.addQuery.files.length - 1) {
    const temp = Data.addPost.addQuery.files[index]
    Data.addPost.addQuery.files[index] = Data.addPost.addQuery.files[index + 1]
    Data.addPost.addQuery.files[index + 1] = temp
  }
}

function getBoard () {
  // 获取板块的分类
  boardApi.getBoard({
    type: 0
  }).then((res) => {
    boardList.value = res
    boardListOptions.value = boardList.value.map(item => ({
      label: item.name,
      value: item.sectionId
    }))
    options.value[0].children = boardList.value.map(item => ({
      label: item.name,
      value: item.sectionId
    }))
  })
}

// 板块获取在上面
function getOptions () {
  // 获取粉丝圈板块
  boardApi.getBoard({
    type: 1
  }).then((res) => {
    boardList.value = res
    options.value[1].children = boardList.value.map(item => ({
      label: item.name,
      value: item.sectionId
    }))
  })
  // 获取前50个帖子
  postApi.getPost({
    pageSize: 50,
    pageNum: 1
  }).then((res) => {
    options.value[2].children = res.list.map(item => ({
      label: item.title ? item.title : '这个帖子没有标题',
      value: item.postId
    }))
    // console.log(res.list)
  })
  // 获取前50个商品
  spuApi.page({
    pageSize: 50,
    pageNum: 1
  }).then((res) => {
    options.value[3].children = res.list[0].spus.map(item => ({
      label: item.spuName,
      value: item.spuId
    }))
    // console.log(res.list[0].spus)
  })
}

onMounted(() => {
  getBoard()
  getOptions()
})
const emits = defineEmits(['workEnd'])
</script>
